import { useEffect, useContext, useState } from 'react';
import Graphin from '@antv/graphin';
import { Behaviors, GraphinContext } from '@antv/graphin';
import { OptionToolbarTwo } from '@/components/Toolbar';
import { Empty } from 'antd';
import ProCard from '@ant-design/pro-card';

const mergeData = (d1, d2) => {
  const distinct = (a, b, trans) => {
    // return [...new Set([...a,...b])]
    const arr = a.concat(b);
    const res = [];
    const s = new Set();
    arr.forEach((i) => {
      const j = trans(i);
      // console.log(j,s)
      if (!s.has(j)) {
        s.add(j);
        res.push(i);
      }
    });
    return res;
  };
  return {
    nodes: distinct(d1.nodes, d2.nodes, (node) => {

      if (node !== undefined)
        return node.id;


    }),
    edges: distinct(d1.edges, d2.edges, (edge) => {
      if (edge !== undefined)
        return edge.source + edge.target;
    }),
  };
};
const ClickBehavior = (props) => {
  const { data, setData, updateData } = props;
  const { graph } = useContext(GraphinContext);
  useEffect(() => {
    // 初始化聚焦到`node-1`
    const handleClick = (evt) => {
      const node = evt.item;
      const model = node.getModel();
      props.onClick(model.id);

      if (!props.updateData) return null;

      graph.updateItem(model.id, {
        style: {
          badges: [
            {
              position: 'LT',
              value: '',
              size: [0, 0],
            },
          ],
        },
      });
      updateData(model?.id).then((obj) => {
        if (obj !== undefined)
          setData(mergeData(data, obj));
      });
      return null;
    };
    // 每次点击聚焦到点击节点上
    graph.on('node:click', handleClick);
    return () => {
      graph.off('node:click', handleClick);
    };
  }, [data, graph, props, props.data, setData, updateData]);
  return null;
};

const defaultNodeStatusStyle = {
  status: {
    hover: {
      halo: {
        visible: true,
      },
    },
  },
};

const defaultNode = {
  type: 'graphin-circle',
  style: {
    keyshape: {
      fill: '#025DF4',
      stroke: '#000',
      fillOpacity: 0.1,
      size: 30,
      lineWidth: '1px',
    },
    label: {
      visible: true,
    },
  },
};
const defaultEdge = {
  style: {
    stroke: '#2498D1',
  },
};
const layout = {
  type: 'gForce',
  minMovement: 0.01,
  maxIteration: 5000,
  preventOverlap: true,
  damping: 0.99,
};

//多元查询的图表
const EquityGraph = (props) => {
  const [height, setHeight] = useState(props.height);
  const [data, setData] = useState(props.data);
  console.log("trtrfgf", data)
  const [focusNodeId, setFocusNodeId] = useState('');
  const { DragCanvas, ActivateRelations } = Behaviors;
  const shouldBegin = () => {
    return true;
  };

  useEffect(() => {
    // graph.clear()
    setData({ nodes: [], edges: [] });
    setData(props.data);
    if (props.data?.defaultFocusNodeId) {
      setFocusNodeId(props.data.defaultFocusNodeId);
    }
  }, [props.data]);
  useEffect(() => {

    props.setFocusNodeId ? props.setFocusNodeId(focusNodeId) : '';
  }, [focusNodeId]);

  return (
    <ProCard ghost style={{ height: height ? height : '85vh' }}>
      {data.nodes?.length ? (

        <Graphin
          data={data}
          layout={layout}
          defaultNode={defaultNode}
          nodeStateStyles={defaultNodeStatusStyle}
          defaultEdge={defaultEdge}
          style={{ height: '100%', width: '100%' }}
        >
          <ClickBehavior
            data={data}
            setData={setData}
            updateData={props.expander}
            onClick={setFocusNodeId}
          />
          <DragCanvas shouldBegin={shouldBegin} />
          <OptionToolbarTwo direction={'horizontal'} refresh={props.refresh ? props.refresh : ''} />
          <ActivateRelations trigger="click"> </ActivateRelations>
        </Graphin>


      ) : (<Empty description="请输入企业名称进行搜索" />)}
    </ProCard>
  )

};

export default EquityGraph;
